package handlers

import (
	"d-serv-go/server/core/bean"
	"d-serv-go/server/core/consts"
	"d-serv-go/server/core/db"
	"d-serv-go/server/core/local"
	"d-serv-go/server/core/serv"
	"d-serv-go/server/core/util"
	json2 "encoding/json"
	"fmt"
	"github.com/bitly/go-simplejson"
	"github.com/gofiber/fiber/v2"
	"strconv"
	"strings"
	"time"
	"unicode"
)

func ServHandler(ctx *fiber.Ctx) error {
	begin := time.Now()

	servId := ""
	act := "query"
	toLogin:= false

	// log.Info("fullUri:%v", fullUri)
	fullUri := ctx.OriginalURL() // 样例: "/search?q=something"
	sa := strings.Split(util.Substr(fullUri, strings.LastIndex(fullUri, "/")+1), ".")
	if len(sa) > 1 && len(sa[0]) > 0 {
		servId = strings.ToUpper(sa[0])
		if len(sa) > 2 && len(sa[1]) > 0 {
			act = Ucfirst(sa[1])
		}
	} else {
		panic(fmt.Sprintf("参数错误 %q", fullUri))
	}
	// 构建context对象
	context := db.NewContext(ctx)
	local.Set(consts.CONTEXT, context)
	paramBean := db.NewParamBean()
	local.Set("fctx", ctx)

	ctx.Context().QueryArgs().VisitAll(func(key, value []byte) {
		paramBean.Set(string(key), string(value))
	})

	if ctx.Accepts("application/json") == "application/json" {
		json, err := simplejson.NewJson(ctx.Body())
		if err == nil {
			for k, v := range json.MustMap() {
				switch v.(type) {
				case int:
					paramBean.Set(k, v.(int))
				case string:
					paramBean.Set(k, v.(string))
				case bool:
					paramBean.Set(k, v.(bool))
				case json2.Number:
					paramBean.Set(k, string(v.(json2.Number)))
				case float64:
					paramBean.Set(k, v.(float64))
				}
			}
		}
	}

	// 所属公司
	ctx.Locals(consts.CMPYCODE, "XD")
	ctx.Locals(consts.PARAMBEAN, paramBean)
	ctx.Locals(consts.SERVID, servId)
	ctx.Locals(consts.COLLABELUP, true)
	servDef, _ := serv.ServUtils.GetServBean(servId)
	// 根据header里内容找到user
	user := context.GetUserBean()
	// 服务需要AUTH认证
	if servDef.GetInt("SERV_AUTH_FLAG", 0) != consts.AUTH_FLAG_NONE {
		if user == nil || user.IsStructEmpty() {
			toLogin = true
		} else {
			context.SetOnlineUser(user)
			toLogin = false
		}
	}
	outBean := bean.NewOutBean()
	if !toLogin {
		paramBean.SetServId(servId).SetAct(act)
		// 调用服务的方法
		outBean = db.ServMgr.Act(paramBean)

	} else {
		outBean.Set("toLogin", true)
	}

	timeUse := time.Now().Sub(begin).Milliseconds()
	outBean.Set(consts.USE_TIME, strconv.FormatInt(timeUse, 10)+"ms")
	// local.RemoveAll()
	//ctx.JSON(outBean)
	json, _ := outBean.MarshalJSON()
	ctx.Send(json)
	return nil
}

//首字符转换为大写
func Ucfirst(str string) string {
	for i, v := range str {
		return string(unicode.ToUpper(v)) + str[i+1:]
	}
	return ""
}
